package com.gjy.redis.util;

import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-06-27 10:43:31
 */
public class JedisUtil {
    private static final Logger log = LoggerFactory.getLogger(JedisUtil.class);
    private static Jedis jedis;

    public static JedisUtil build(Jedis j) {
        jedis = j;
        return new JedisUtil();
    }

    public boolean lock(String key, String value, String timeout) {
        String script = "if (redis.call('exists', KEYS[1]) == 1) then\n" +
                "    return 0;\n" +
                "else\n" +
                "    return redis.call('set', KEYS[1], ARGV[1], 'ex', ARGV[2]);\n" +
                "end";
        String o = jedis.eval(script, Lists.newArrayList(key), Lists.newArrayList(value, timeout)).toString();
        log.info("加锁: [{}-{}: {}]", key, value, o);
        return !o.equals("0");
    }

    public boolean unlock(String key, String value) {
        String script = "if (redis.call('get', KEYS[1]) == ARGV[1]) then\n" +
                "    return redis.call('del', KEYS[1]);\n" +
                "else\n" +
                "    return 0;\n" +
                "end";
        String o = jedis.eval(script, Lists.newArrayList(key), Lists.newArrayList(value)).toString();
        log.info("解锁: [{}-{}: {}]", key, value, o);
        return !o.equals("0");
    }

}
